'use strict';

const { BaseController } = require('@/core');
const fs = require('fs-extra');

const config = {
  path: 'storage',
  key: 'bestlyg',
};
class StorageController extends BaseController {
  getPath(...paths) {
    return this.ctx.helper.resolve(config.path, ...paths);
  }
  async ensureRootDir() {
    await fs.ensureDir(this.getPath());
  }
  async show() {
    this.ensureRootDir();
    await (this.ctx.params.id === config.key ? this.get_root() : this.get_common());
  }
  async get_root() {
    const files = await fs.readdir(this.getPath());
    if (!files) return await this.result(Promise.reject(new Error()));
    const cache = {};
    for (const file of files) {
      const data = await fs.readJson(this.getPath(file));
      if (!data) continue;
      cache[file.replace('.json', '')] = data;
    }
    return await this.result(Promise.resolve(cache));
  }
  async get_common() {
    const { ctx } = this;
    const id = ctx.params.id;
    return await this.result(
      fs.readJson(this.getPath(`${id}.json`)).then(
        data => data,
        () => null
      )
    );
  }
  async create() {
    this.ensureRootDir();
    const { ctx } = this;
    const { key, data } = ctx.request.body;
    if (!data || !key || key === config.key) {
      await this.result();
    } else {
      await this.result(
        fs.writeJson(this.getPath(`${key}.json`), data, {
          spaces: 4,
        })
      );
    }
  }
  async destroy() {
    this.ensureRootDir();
    const { ctx } = this;
    const id = ctx.params.id;
    if (id === config.key) {
      await this.result(fs.emptyDir(this.getPath()));
    } else {
      await this.result(fs.remove(this.getPath(`${id}.json`)));
    }
  }
}

module.exports = StorageController;
